﻿using System;
using System.Globalization;

namespace Delphi.Janus.Util {
    public static class StringExtension {
        public static string GetLast(this string source, int tailLength) {
            if(tailLength >= source.Length) {
                return source;
            }
            return source.Substring(source.Length - tailLength);
        }

        public static string GetFirst(this string source, int headLength) {
            if(headLength >= source.Length) {
                return source;
            }
            return source.Substring(0, headLength);
        }

        public static string RemoveLast(this string source, int tailLength) {
            if (tailLength >= source.Length) {
                return source;
            } 
            return source.Substring(0, source.Length - tailLength);
        }

        public static decimal YahooConvert(this string number) {
            string extension = number.GetLast(1);

            int n;
            Decimal factor = 1;
            Decimal amount = 0;
            if (int.TryParse(extension, out n)) {
                // if the last char is a number --> nothing to convert!
                Decimal.TryParse(number, NumberStyles.Any, new CultureInfo("en-US"), out amount);
                return amount;
            } else if(number.Equals("N/A") || number.Equals("NaN")) {
                return 0;
            }

            string reaminingNumber = number.GetFirst(number.Length - 1);
            
            switch (extension) {
                case "B":
                    factor = 1000000000;
                    break;
                case "M":
                    factor = 1000000;
                    break;
                case "K":
                    factor = 1000;
                    break;
                case "%":
                    factor = 0.01m;
                    break;
                default:
                    factor = 1;
                    break;
            }

            // Decimal.TryParse(cell.InnerText, NumberStyles.Any, new CultureInfo("en-US"), out amountDec)) {
            Decimal.TryParse(reaminingNumber, NumberStyles.Any, new CultureInfo("en-US"), out amount);

            return amount * factor;
        }
    }
}
